package com.tanhua.server.server;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.CommentsApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domian.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommentsService {

    @DubboReference
    private CommentsApi commentsApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private MovementApi movementApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String caonima = "caonima";

    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //根据动态ID找到评论人
        List<Comment> commentList = commentsApi.find(movementId, CommentType.COMMENT, page, pagesize);
        //查看评论人是否为空，如果为空回
        if (CollUtil.isEmpty(commentList)) {
            return new PageResult();
        }
        //根据评论人找到评论人信息
        List<Long> userIds = CollUtil.getFieldValues(commentList, "userId", long.class);
        //封装VO对象返回
        List<CommentVo> commentVoList = new ArrayList<>();
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, null);
        for (Comment comment : commentList) {
            UserInfo userInfo = userInfoMap.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo init = CommentVo.init(userInfo, comment);
                String key = Constants.MOVEMENTS_INTERACT_KEY + comment.getId();
                String hashKey = caonima+ UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
                    init.setHasLiked(1);
                }
                commentVoList.add(init);
            }
        }
        return new PageResult(page, pagesize, 01, commentVoList);
    }

    public void saveComments(String movementId, String comment) {
        //在comment表里面添加一条评论数据
        //在movement表里面让评论字段commentCount+1
        Long userId = UserHolder.getUserId();
        Comment commentrusult = new Comment();
        ObjectId objectId = new ObjectId(movementId);
        commentrusult.setPublishId(objectId);
        commentrusult.setCommentType(CommentType.COMMENT.getType());
        commentrusult.setContent(comment);
        commentrusult.setUserId(userId);
        commentrusult.setCreated(System.currentTimeMillis());

        //获取评论数
        Integer all = commentsApi.save(commentrusult);
        log.info("评论数有={}", all);
    }

    public Integer list(String movementId) {
        //获取本账户ID
        Long userId = UserHolder.getUserId();
        //查询是否已经点赞
        boolean hasComment = commentsApi.hasComment(movementId, userId, CommentType.LIKE);
        //如果已经点餐 则抛出异常
        if (hasComment) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //创建comment对象保存进数据库
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(userId);
        comment.setCreated(System.currentTimeMillis());
        Integer save = commentsApi.save(comment);

        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();

        redisTemplate.opsForHash().put(key, hashKey, "1");

        return save;
    }

    /**
     * 取消点赞
     *
     * @param movementId
     * @return
     */
    public Integer dislike(String movementId) {
        Long userId = UserHolder.getUserId();
        //判断是否未点赞
        boolean hasComment = commentsApi.hasComment(movementId, userId, CommentType.LIKE);
        //如果未点赞 则抛出异常
        if (!hasComment) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //删除comment表里面的点赞记录
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        Integer all = commentsApi.delete(comment);

        //删除redis里面的hashkey
        String key = Constants.MOVEMENTS_INTERACT_KEY + comment.getPublishId().toHexString();
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();

        redisTemplate.opsForHash().delete(key, hashKey);
        return all;
    }


    public Integer commentslike(String PublishId) {
        Long userId = UserHolder.getUserId();
        //查询评论表comment，判断是否已经给评论点赞
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setPublishId(new ObjectId(PublishId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setCreated(System.currentTimeMillis());
        Boolean b = commentsApi.likeCount(comment);
        if (b){
            throw new BusinessException(ErrorResult.likeError());
        }

        //依靠评论ID，在mongDB里面找到评论数据,然后更新点赞评论的数据+1 之后返回点赞评论的点赞数\
        //然后在comment表里面添加评论点赞数据
        //通过方法得到评论点赞的id  缓存到redis
        //Comment comment2 = commentsApi.commentslike(comment);

        Map<String,Comment>  map = commentsApi.commentslike(comment);

        Comment comment1 = map.get("comment");
        Comment andModify = map.get("andModify");

        String key = Constants.MOVEMENTS_INTERACT_KEY + comment1.getPublishId();
        String hashKey = caonima+ UserHolder.getUserId();

        redisTemplate.opsForHash().put(key, hashKey, "1");

        return andModify.getLikeCount();
    }

    public Integer commentsdislike(String PublishId) {
        //根据评论ID找到评论数据，然后更新点赞评论的数据-1，返回评论点赞数
        Long userId = UserHolder.getUserId();
        //查询评论表comment，判断是否已经给评论点赞
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setPublishId(new ObjectId(PublishId));
        comment.setCommentType(CommentType.LIKE.getType());
        Boolean b = commentsApi.likeCount(comment);
        if (!b){
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //依靠评论ID，在mongDB里面找到评论数据,然后更新点赞评论的数据+1 之后返回点赞评论的点赞数\
        //然后在comment表里面删除评论点赞数据
        Map<String,Comment>  map = commentsApi.commentsdislike(comment);

        Comment comment1 = map.get("comment");
        Comment andModify = map.get("andModify");

        //删除redis里面的hashkey
        String key = Constants.MOVEMENTS_INTERACT_KEY + comment1.getPublishId();
        String hashKey = caonima + UserHolder.getUserId();

        redisTemplate.opsForHash().delete(key, hashKey);

        return andModify.getLikeCount();
    }
}
